package com.kma.summer2012.client.presenters.mainPage;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.kma.summer2012.client.CrumbsEventBus;
import com.kma.summer2012.client.ExceptionHandling.CrumbsRPCServiceException;
import com.kma.summer2012.client.ExceptionHandling.ExceptionProcessor;
import com.kma.summer2012.client.events.FillCellTableEvent;
import com.kma.summer2012.client.events.UpdateCellTableEvent;
import com.kma.summer2012.client.presenters.Presenter;
import com.kma.summer2012.client.presenters.header.HeaderPresenter;
import com.kma.summer2012.client.services.AbstractCallBack;
import com.kma.summer2012.client.services.catalogOfWorks.CrumbsCatalogOfWorksService;
import com.kma.summer2012.client.services.request.CrumbsRequestService;
import com.kma.summer2012.shared.model.UICrumbsRequest;
import com.kma.summer2012.shared.model.UICrumbsUser;
import com.kma.summer2012.shared.model.UICrumbsWorkItem;

import java.util.List;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: EUGENE
 * Date: 2/10/13
 * Time: 7:11 PM
 * To change this template use File | Settings | File Templates.
 */
public class MainPagePresenter implements Presenter, IMainPagePresenter {
    private final Display display;
    private CrumbsEventBus eventBus;
    private String position = "";
    private HasWidgets container;

    public void go(HasWidgets container) {
        this.container = container;
        container.clear();
        container.add(display.asWidget());
    }

    public MainPagePresenter(Display display) {
        this.display = display;
        this.eventBus = CrumbsEventBus.getInstance();
        this.bind();
        this.fillDataGrid(display.getTableID());
        /*
        try{
            throw new CrumbsRPCServiceException("I'm checking you");
        }catch (Exception e){
            ExceptionProcessor.getInstance().processServiceFailure(e);
        }
          */
    }

    public void bind() {
        this.eventBus.addHandler(UpdateCellTableEvent.getType(), new UpdateCellTableEvent.UpdateCellTableEventHandler() {
            @Override
            public void onFillCellTable(UpdateCellTableEvent event) {
                MainPagePresenter.this.fillDataGrid(event.tableID);
            }
        });
    }

    public void fillDataGrid(final Integer tableID) {
        if (display.getTableID().equals(tableID)) {
            UICrumbsUser user = HeaderPresenter.getUser();
            CrumbsRequestService.App.getInstance().getAllForUser(user, new AbstractCallBack<List<UICrumbsRequest>>() {
                @Override
                public void onSuccess(List<UICrumbsRequest> uiCrumbsRequests) {
                    eventBus.fireEvent(new FillCellTableEvent(uiCrumbsRequests, tableID));
                }
            });
        }
    }
}
